package com.mq.exchange;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeoutException;

/**
 * topic  exchange
 *
 * @author xwj
 * @date 2019/3/1
 */
public class EmitLogTopic {
    private static final String EXCHANGE_NAME = "topic_logs";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "topic");

        // 获取日志信息
        String logInfo = getLogInfo();

        String routingKey = getRoutingKey(logInfo);

        channel.basicPublish(EXCHANGE_NAME, routingKey, null, logInfo.getBytes());

        System.out.println("send logs:" + logInfo + ",routingKey:" + routingKey);

        channel.close();
        connection.close();
    }

    private static String getLogInfo() {
        Random random = new Random();
        int infoNum = random.nextInt(3) + 1;
        StringBuilder log = new StringBuilder();
        for (int i = 0; i < infoNum; i++) {
            log.append(".");
        }
        return log.toString();
    }

    private static String getRoutingKey(String logInfo) {
        if (logInfo.length() == 1) {
            return "safe.info.routing";
        } else if (logInfo.length() == 2) {
            return "safe.warning.routing";
        }
        return "danger.error.routing";
    }
}
